// 在文件顶部添加缺失的React和hooks导入
import React, { useState, useRef, useEffect } from 'react';
import {MoreOutlined, PlusOutlined} from '@ant-design/icons'
import {
    Button,
    Col,
    Flex,
    Form,
    Input,
    Row,
    Select,
    Typography,
    Table,
    Modal,
    Switch,
    Space,
    Divider,
    Dropdown,
    message
} from 'antd'
import MyDatePicker from '../components/MyDatePicker'
import {useNavigate} from 'react-router-dom'
import {
    tagList,
    getAllTags,
    getChildTagsByParentId,
    getTagById,
    deleteTag,
    updateTag,
    createTag,
    updateTagStatus // 添加这一行
} from '../service/tag'
import {shopList} from "../service/shop";

export default function TagList() {
    const [isShow, setIsShow] = useState(false)
    const [isShow2, setIsShow2] = useState(false)
    const navigate = useNavigate()
    // 保存选择的日期
    const [selectedDateString, setSelectedDateString] = useState(null)
    const [form] = Form.useForm()
    const [form2] = Form.useForm()
    // 创建表单的引用
    const formRef = useRef()
    const formRef2 = useRef()
    // 模态框
    const [isModalOpen01, setIsModalOpen01] = useState(false)
    const [isModalOpen02, setIsModalOpen02] = useState(false)

    // 搜索条件
    const [condition, setCondition] = useState({})
    // 保存页码
    const [pageNo, setPageNo] = useState(1)
    const [total, setTotal] = useState(0)
    const [tagLists, setTagLists] = useState([]) // 状态变量定义

    // 添加handleStatusChange函数
    const handleStatusChange = async (checked, record) => {
        // 保存当前记录的原始状态，用于可能的恢复操作
        const originalStatus = record.status;
        const originalChecked = originalStatus === 0; // 确保originalChecked和checked类型一致

        // 显示加载状态
        const loadingKey = Date.now();
        message.loading({ content: '状态更新中...', key: loadingKey, duration: 0 });

        try {
            // 根据checked状态设置新状态值（0表示开启，1表示关闭）
            const newStatus = checked ? 0 : 1;

            console.log(`尝试更新标签ID: ${record.id}, 从状态: ${originalStatus} 更新到: ${newStatus}`);

            // 立即更新本地状态，提供即时反馈
            setTagLists(prevLists =>
                prevLists.map(tag =>
                    tag.id === record.id ? { ...tag, status: newStatus } : tag
                )
            );

            // 调用API更新状态
            // 添加超时处理
            const timeoutPromise = new Promise((_, reject) =>
                setTimeout(() => reject(new Error('API调用超时')), 10000)
            );

            // 检查参数类型和格式
            console.log(`API调用参数: id=${record.id}, status=${newStatus}`);

            const res = await Promise.race([
                updateTagStatus(record.id, newStatus),
                timeoutPromise
            ]);

            console.log('API调用结果:', res);

            // 如果更新成功，触发重新请求API获取最新数据
            if (res && (res.code === 0 || res.success)) {
                // 使用函数式更新确保获取最新状态值
                setN(prevN => prevN + 1);
                message.destroy(loadingKey); // 销毁加载提示
                message.success({ content: '标签状态更新成功', key: 'success' });
            } else {
                // API调用失败，使用函数式更新恢复状态
                setTagLists(prevLists =>
                    prevLists.map(tag =>
                        tag.id === record.id ? { ...tag, status: originalStatus } : tag
                    )
                );
                message.destroy(loadingKey); // 销毁加载提示
                message.error({
                    content: `状态更新失败: ${res?.msg || res?.message || '服务器返回未知错误'}`,
                    key: 'error'
                });
            }
        } catch (error) {
            console.error('更新标签状态失败:', error);
            // 异常情况下也使用函数式更新恢复状态
            setTagLists(prevLists =>
                prevLists.map(tag =>
                    tag.id === record.id ? { ...tag, status: originalStatus } : tag
                )
            );
            message.destroy(loadingKey); // 销毁加载提示
            message.error({
                content: `状态更新失败: ${error.message || '网络异常或服务器错误'}`,
                key: 'error'
            });
        }
    };
    
    // 处理删除标签 - 确保在组件内部定义
    const handleDelete = async (record) => {
        try {
            // 显示确认对话框
            const confirmResult = window.confirm(`确定要删除标签"${record.tagName}"吗？`);
            
            if (confirmResult) {
                // 调用API删除标签
                const res = await deleteTag({ id: record.id });
                console.log('删除标签结果:', res);
            
                // 如果删除成功，刷新标签列表
                if (res.code == 0) {
                    // 从本地状态中移除删除的标签
                    const updatedLists = tagLists.filter(item => item.id !== record.id);
                    setTagLists(updatedLists); // 正确更新状态
                    // 可以添加成功提示
                    // message.success('标签删除成功')
                } else {
                    // 如果删除失败，提示用户
                    console.error('删除标签失败:', res.msg);
                    // 可以添加message提示
                    // message.error(res.msg || '删除标签失败')
                }
            }
        } catch (error) {
            console.error('删除标签发生异常:', error);
            // 可以添加message提示
            // message.error('操作失败，请重试')
        }
    }
    
    /*
    {
      id: 1,
      name: '旅行',
      group: '内容标签',
      createTime: '2023-01-01',
      description: '这是一个关于旅行的标签',
      status: true
    },
    {
      id: 2,
      name: '美食',
      group: '内容标签',
      createTime: '2024-04-21',
      description: '这是一个关于美食的标签',
      status: true
    },
    {
      id: 3,
      name: '购物',
      group: '内容标签',
      createTime: '2023-12-21',
      description: '这是一个关于购物的标签',
      status: false
    },
    {
      id: 4,
      name: '优惠',
      group: '活动标签',
      createTime: '2023-11-05',
      description: '这是一个关于优惠的标签',
      status: true
    },
    {
      id: 5,
      name: '活动',
      group: '活动标签',
      createTime: '2023-06-30',
      description: '这是一个关于活动的标签',
      status: false
    },
    {
      id: 6,
      name: '秒杀',
      group: '活动标签',
      createTime: '2023-01-01',
      description: '这是一个关于秒杀的标签',
      status: true
    }
  ])
  */

    const request = async () => {
        const res = await getAllTags({
            ...condition,
            pageNo,
            pageSize: 10
        })
        console.log(res)

        // 移除状态过滤条件，显示所有标签（包括状态为0和1的）
        setTagLists(res.data.objects);
        setTotal(res.data.total);
    }


    // 用于更新列表
    const [n, setN] = useState(1)

    useEffect(() => {
        request();
    }, [n])

    return (
        <>
            <Row className="info">
                <Col span={24}>
                    <Flex justify={'space-between'}>
                        <Typography.Title level={3}>信息管理</Typography.Title>
                        <Button
                            type="primary"
                            icon={<PlusOutlined/>}
                            onClick={() => {
                                // setIsModalOpen02(true)
                                navigate('/admin/tag/add')
                            }}
                        >
                            新增标签
                        </Button>
                    </Flex>
                </Col>
            </Row>
            <Row>
                <Col span={3}>
                    <div className="container" style={{marginRight: 0, height: '100%'}}>
                        <Space direction="vertical">
                            <Button
                                type="primary"
                                block
                                onClick={() => {
                                    setIsModalOpen02(true)
                                }}
                            >
                                新增分类
                            </Button>
                            <Input.Search placeholder="请输入搜索关键字"/>
                            <Flex
                                justify={'space-between'}
                                style={{
                                    padding: '5px 10px',
                                    borderRadius: 5,
                                    backgroundColor: '#EEE',
                                    position: 'relative'
                                }}
                            >
                <span
                    style={{cursor: 'pointer', color: '#666'}}
                    onClick={() => {
                        setIsShow(!isShow)
                    }}
                >
                  用户标签
                </span>
                                <PlusOutlined
                                    onClick={() => setIsModalOpen01(true)}
                                    style={{
                                        marginLeft: 24,
                                        fontSize: 10,
                                        position: 'absolute',
                                        right: 30,
                                        top: 9
                                    }}
                                />
                                <Dropdown
                                    trigger={['click']}
                                    menu={{
                                        items: [
                                            {
                                                label: '重命名',
                                                key: 'rename'
                                            },
                                            {
                                                label: '删除',
                                                key: 'delete'
                                            }
                                        ]
                                    }}
                                >
                                    <MoreOutlined/>
                                </Dropdown>
                            </Flex>
                            <Flex
                                vertical
                                style={{
                                    paddingLeft: '10px',
                                    lineHeight: '22px',
                                    display: !isShow && 'none'
                                }}
                            >
                                <span>旅游</span>
                                <span>美食</span>
                                <span>娱乐</span>
                            </Flex>
                            <Flex
                                justify={'space-between'}
                                style={{
                                    padding: '5px 10px',
                                    borderRadius: 5,
                                    backgroundColor: '#EEE',
                                    position: 'relative'
                                }}
                            >
                <span
                    style={{cursor: 'pointer', color: '#666'}}
                    onClick={() => {
                        setIsShow2(!isShow2)
                    }}
                >
                  内容标签
                </span>
                                <PlusOutlined
                                    onClick={() => setIsModalOpen01(true)}
                                    style={{
                                        marginLeft: 24,
                                        fontSize: 10,
                                        position: 'absolute',
                                        right: 30,
                                        top: 9
                                    }}
                                />
                                <Dropdown
                                    trigger={['click']}
                                    menu={{
                                        items: [
                                            {
                                                label: '重命名',
                                                key: 'rename'
                                            },
                                            {
                                                label: '删除',
                                                key: 'delete'
                                            }
                                        ]
                                    }}
                                >
                                    <MoreOutlined/>
                                </Dropdown>
                            </Flex>
                            <Flex
                                vertical
                                style={{
                                    paddingLeft: '10px',
                                    lineHeight: '22px',
                                    display: !isShow2 && 'none'
                                }}
                            >
                                <span>铁公鸡</span>
                                <span>羊毛党</span>
                                <span>购物狂</span>
                            </Flex>
                        </Space>
                    </div>
                </Col>
                <Col span={21}>
                    <Row className="container">
                        <Col span={24}>
                            <Form layout="inline" onFinish={() => {
                            }}>
                                <Form.Item label="标签名称：" name="storeName">
                                    <Input/>
                                </Form.Item>
                                <Form.Item label="启用状态：" name="storeAddress">
                                    <Select
                                        placeholder="状态选择"
                                        options={[
                                            {
                                                value: '',
                                                label: '全部'
                                            }
                                        ]}
                                    />
                                </Form.Item>
                                <Form.Item label="计算方式：" name="calc">
                                    <Select
                                        placeholder="方式选择"
                                        options={[
                                            {
                                                value: '',
                                                label: '全部'
                                            }
                                        ]}
                                    />
                                </Form.Item>
                                <Form.Item label="更新时间">
                                    <MyDatePicker
                                        selectedDateString={selectedDateString}
                                        setSelectedDateString={setSelectedDateString}
                                    />
                                </Form.Item>

                                <Form.Item>
                                    <Button type="default" htmlType="reset">
                                        重置
                                    </Button>
                                </Form.Item>
                                <Form.Item>
                                    <Button type="primary" htmlType="submit">
                                        查询
                                    </Button>
                                </Form.Item>
                            </Form>
                        </Col>
                    </Row>
                    <Row className="container">
                        <Col span={24}>
                            <Typography.Paragraph style={{fontSize: 16}}>
                                标签列表
                            </Typography.Paragraph>
                        </Col>
                        <Col span={24}>
                            <Table
                                rowKey="id"
                                dataSource={tagLists}
                                columns={[
                                    {
                                        title: '标签ID',
                                        dataIndex: 'id',
                                        key: 'id'
                                    },
                                    {
                                        title: '标签名称',
                                        dataIndex: 'tagName',
                                        key: 'tagName'
                                    },
                                    {
                                        title: '标签分组',
                                        dataIndex: 'tagType',
                                        key: 'tagType',
                                        render: (_, record) => {
                                            return record.tagType === 0 ? '内容标签' : '用户标签'
                                        }
                                    },
                                    {
                                        title: '创建时间',
                                        dataIndex: 'createAt',
                                        key: 'createAt'
                                    },
                                    {
                                        title: '内容描述',
                                        dataIndex: 'tagDesc',
                                        key: 'tagDesc'
                                    },
                                    {
                                        title: '状态',
                                        dataIndex: 'status',
                                        key: 'status',
                                        render: (_, record) => {
                                            return <Switch
                                                checked={record.status === 0}
                                                onChange={(checked) => handleStatusChange(checked, record)}
                                            />
                                        }
                                    },
                                    {
                                        title: '操作',
                                        dataIndex: 'op',
                                        key: 'op',
                                        align: 'center',
                                        render: (_, record) => {
                                            return (
                                                <span className="op">
                          <a onClick={() => {
                              navigate('/admin/tag/add', { state: { id: record.id, isEditing: true } })
                          }}>编辑</a>
                          {/* 修改后 */}
                          <a style={{marginLeft: 10}} onClick={() => handleDelete(record)}>删除</a>
                        </span>
                                            )
                                        }
                                    }
                                ]}
                            />
                        </Col>
                    </Row>
                </Col>
            </Row>

            <Modal
                title="新增标签分组"
                open={isModalOpen01}
                onOk={() => {
                    formRef.current.submit()
                    // navigate('/admin/tag/add')
                }}
                onCancel={() => setIsModalOpen01(false)}
                maskClosable={false}
                width={500}
                destroyOnClose
            >
                <Divider/>
                <Form
                    form={form}
                    ref={formRef}
                    onFinish={() => {
                        setIsModalOpen01(false)
                    }}
                    preserve={false}
                >
                    <Form.Item
                        label="标签分组"
                        name="tagName"
                        rules={[
                            {
                                required: true,
                                message: '请输入标签分组'
                            }
                        ]}
                    >
                        <Input placeholder="请输入标签分组名称"/>
                    </Form.Item>
                </Form>
            </Modal>
            <Modal
                title="新增分类"
                open={isModalOpen02}
                onOk={() => {
                    setIsModalOpen02(false)
                    // formRef2.current.submit()
                }}
                onCancel={() => setIsModalOpen02(false)}
                maskClosable={false}
                width={500}
                destroyOnClose
            >
                <Divider/>
                <Form.Item
                    label="标签分类"
                    ref={formRef2}
                    form={form2}
                    name="tagName"
                    rules={[
                        {
                            required: true,
                            message: '请输入标签分类'
                        }
                    ]}
                >
                    <Input placeholder="请输入标签分类名称"/>
                </Form.Item>
            </Modal>
        </>
    )
}